
const { user } = require("../../../mock-info");
const { staticUrl } = require("../../../services/config");

// pages/personal/detail/index.js
const app = getApp();
const { uploadFile } = app._require("utils/upload.file");
const { AskPage } = app._require('common/index');
const formMixin = app._require("mixins/form.mixin.js").default;
AskPage({
    /**
     * 页面的初始数据
     */
    name: "taskForm",
    mixins: [formMixin],


  /**
   * 页面的初始数据
   */
  data: {
    itemTypeList: ["头像","修改密码","解绑微信"],
    itemUnBindTypeList: ["头像","修改密码","绑定微信"],
    itemTypeImgList:["mine_detail_user.png","mine_detail_lock.png","mine_detail_wechat.png"],
    itemTypeUnBindImgList:["mine_detail_user.png","mine_detail_lock.png","mine_detail_link.png",],
    actions: [{ name: '修改头像' }, { name: '恢复默认头像' }],
    show: false,
    wechatShow:false,
    cancleBind:false,
    url:"",
    user:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(this.user);
    let firstInfoName =  app.user.userInfo.name;
    let name = firstInfoName? firstInfoName.substring(0,1):"";
    var  headPortrait = app.user.userInfo.headPortrait;
    headPortrait=headPortrait.replace((staticUrl+"/"), '');
    headPortrait=headPortrait.replace((staticUrl), '');
    // console.log(headPortrait);
    if(headPortrait.length>0){
      if(headPortrait.substring(0,1) !="/"){
        headPortrait = "/" + headPortrait
    }
        headPortrait = staticUrl + headPortrait;
    }
    this.setData({
      user:app.user,
      firstName:name,
      url:headPortrait,
      openId:app.user.userInfo.openId
    });
  },

  getCredentials() {
    return new Promise(async (resolve, reject) => {
        const response = await this.$_server("cosAuth");
        let { data } = response;
        if (data.code !== 200) {
            reject(data);
        }
        resolve(data.data);
    });
},
   itemClick:function(e){
    console.log(e);
    var index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    console.log(item)
    if(item == "头像"){
      this.setData({
        "show":true
    });
    }else if(item=="修改密码"){
      wx.navigateTo({
        url:"/pages/change-password/index"
    }) 
    }else if(item=="解绑微信"){
      this.setData({
        "cancleBind":true
      });
      
    }else if(item=="绑定微信"){
      
      this.setData({
        "wechatShow":true
      });
    }
   },
   onCloseAction:function(){
    this.setData({
      "show":false,
      "wechatShow":false,
      "cancleBind":false
  });
   },


  onSelectAction:function(e){
    
     var name = e.detail.name;
     var user = app.user;
    //  console.log(name);
    if(name == "修改头像"){
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res)=> {
          // tempFilePath可以作为img标签的src属性显示图片
                    const tempFiles = res.tempFiles;
                    this.upload(tempFiles);

        }
      })      
    }else if(name == "恢复默认头像"){
      // var user = app.user;
      user.userInfo.headPortrait = "";
      this.setData({
        user:user,
        url:""
      });
      this.updateUser("");
      console.log(name);
    }
   },

  async upload(files) {
    wx.showLoading({
        title: "上传中...",
        mask: true,
    });
    try {

      // var timestamp = Date.parse(new Date());
      // var date = new Date(timestamp);
      // //获取年份  
      // var Y =date.getFullYear();
      // //获取月份  
      // var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
      // //获取当日日期 
      // var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); 
      // // console.log("当前时间：" + Y + '年'  + M+ '月' + D+ '日' );
      // // console.log()
      // const time = Y +"-"+M+"-"+D;

        //上传头像
        const nowTime = new Date();
        const uploadFilePath = "user-picture"+"/img"+"/"+nowTime.format("yyyy-MM-dd")+"/"
      
        const uploadList = files.map(file => ({
            dir: uploadFilePath,//this.data.uploadImageProps.dir + nowTime.format("yyyy/MM/dd") + "/",
            filePath: file.path || "",
            size: file.size,
            _id: "choose",
        }));
        let url = "";
        console.log("getCredentials",uploadList);
        const _response = await uploadFile(uploadList, {
            limit: 10 * 1024 * 1024,
            timeout: 60*1000,
            action: this.data.actionUrl,
            initAuth: this.getCredentials.bind(this),
            oscPath:"file",
            onReady: files => {
                this.triggerEvent("update", {
                    type: "upload",
                    list: files,
                    item: null,
                });
            },
            beforeUpload: (curFile, files) => {
                this.triggerEvent("update", {
                    type: "upload",
                    list: files,
                    item: curFile,
                });
            },
            afterUpload: (curFile, files, errors) => {
                if (errors && errors.length > 0) {
                    wx.askShowToastEx({
                        icon: "none",
                        title: "上传文件只能在" + 10 + "M以内",
                    });
                }
                url = curFile;
                this.triggerEvent("update", {
                    type: "upload",
                    list: files,
                    item: curFile,
                });
            },
        });
        
        wx.hideLoading();
        this.updateUser(url.fileName);
        console.log(url.firstName);
        // this.$emit("setModel", { value: url.src });
    } catch (error) {
        wx.hideLoading();
        console.log(error);
    }
  },
  async updateUser(files){
    // console.log(files);
    if(files.substring(0,1) !="/" &&files.length>0){
      files = "/" + files
    }
    let response = await this.$_server(
      "user/userUpdate", {
        data: {
          headPortrait: files,//url.fileName,
          id:app.user.userInfo.id,
          // governmentIds:[(app.user.userInfo.governmentId)],
          // governmentId:(app.user.userInfo.governmentId)
        },
    }
    );

    let { data } = response;
    console.log(data);
    if (data.code !== 200) {
        wx.askShowToastEx({
          title: data.message||"系统异常",
          icon:"none"
        })
        throw data;
    }else{
      // var user = app.user;
       var headPortrait = staticUrl+'/'+ files;//url.fileName;
       app.user.userInfo.headPortrait = headPortrait;
       console.log(files);
      // user.userInfo.avatar = "";
      if(files.length>0){
        console.log(files);
        this.setData({
          user:app.user,
          url:headPortrait
        });
      }else{
        app.user.userInfo.headPortrait= "";
      }

      var userStorage = wx.getStorageSync("user");
      userStorage.userInfo.headPortrait = app.user.userInfo.headPortrait;
      wx.setStorage({
        data: userStorage,
        key: 'user',
      })
      // console.log(userStorage);
      // app.
    }

    var message  = data.message;
    wx.askShowToastEx({
      icon: "none",
      title: message,
    });
  },
  //图片加载出错，替换为默认图片
   avatarError(error){
    console.log("1111111");
    this.setData({
        // Url:'/assets/error.png'
        url:'/assets/error.png'
    })
  },
  //
  getUserInfo(res){
    console.log(res);
    wx.showModal({
      title: "",
      content: "确认绑定微信?",
      success: (res)=> {
          if (res.confirm) {
      
            this.bindWxAction();
          } else if (res.cancel) {
              console.log("用户点击取消");
          }
      },
  });
  
  },
  cancleBindWx () {
    this.setData({
      "cancleBind":false
    })
    this.bindWx("");
  },
  bindWxAction(){

    let openId = app.user.userInfo.openId;
    let wxcode = app.user.wxcode;
    console.log(wxcode);
    if(openId.length==0){
      // if(wxcode.length==0){
       wx.login({
      timeout: 1110,
      success:res=>{
        // console.log(res)
        this.getOpenId(res.code);
      }
    }) 
    }else{
      this.bindWx(openId);
    }


  },
  async getOpenId(code){
    console.log(code);
    const response = await this.$_server("user/openId", {
      data: {
        code: code,
      },
  });
  let { data } = response;
  console.log(data);
  if (data.code !== 200) {
      // throw data;
      wx.askShowToastEx({
        title: data.message,
        icon: "none",
  
      })
      return;
  }
  
  let openid = data.data;
  console.log(openid);

  this.bindWx(openid);

  },
  async bindWx (openid) {
    const response = await this.$_server("user/bind", {
      data: {
        openId: openid,
      },
  });
  let { data } = response;

  if(data.code ==200){
    this.setData({
      openId:openid
    })

    app.user.userInfo.openId = openid;
    var userStorage = wx.getStorageSync("user");
    userStorage.userInfo.openId =openid;
    wx.setStorage({
      data: userStorage,
      key: 'user',
    })

  }

  }


})